package com.wilmer.TecherLessonPlan.service.impl;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.ChatCompletionResponse;
import com.unfbx.chatgpt.entity.chat.Message;
import com.unfbx.chatgpt.entity.chat.ResponseFormat;
import com.wilmer.TecherLessonPlan.domain.vo.LessonPlan;
import com.wilmer.TecherLessonPlan.listener.LessonSseStreamFastGptListener;
import com.wilmer.TecherLessonPlan.utils.BuildLessonPlanUtil;
import com.wilmer.ai.client.StreamClient;
import com.wilmer.ai.config.LocalCache;
import com.wilmer.ai.listener.SseStreamFastGptListener;
import com.wilmer.common.utils.DateUtils;
import com.wilmer.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wilmer.TecherLessonPlan.mapper.YwLessonPlanMapper;
import com.wilmer.TecherLessonPlan.domain.YwLessonPlan;
import com.wilmer.TecherLessonPlan.service.IYwLessonPlanService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

/**
 * 教案管理Service业务层处理
 *
 * @author hans
 * @date 2024-04-27
 */
@Slf4j
@Service
public class YwLessonPlanServiceImpl implements IYwLessonPlanService
{
    @Autowired
    private YwLessonPlanMapper ywLessonPlanMapper;
    @Resource
    private BuildLessonPlanUtil lessonPlanUtil;
    @Resource
    private StreamClient client;




    @Override
    public SseEmitter createSse(String uid) {
        //默认30秒超时,设置为0L则永不超时
        SseEmitter sseEmitter = new SseEmitter(0L);
        //完成后回调
        sseEmitter.onCompletion(() -> {
            log.info("[{}]结束连接...................", uid);
            LocalCache.CACHE.remove(uid);
        });
        //超时回调
        sseEmitter.onTimeout(() -> {
            log.info("[{}]连接超时...................", uid);
        });
        //异常回调
        sseEmitter.onError(
                throwable -> {
                    try {
                        log.info("[{}]连接异常,{}", uid, throwable.toString());
                        sseEmitter.send(SseEmitter.event()
                                .id(uid)
                                .name("发生异常！")
                                .data(Message.builder().content("发生异常请重试！").build())
                                .reconnectTime(3000));
                        LocalCache.CACHE.put(uid, sseEmitter);
                    } catch (IOException e) {
                        log.info(String.valueOf(e));
                    }
                }
        );
        LocalCache.CACHE.put(uid, sseEmitter);
        log.info("[{}]创建sse连接成功！", uid);
        return sseEmitter;
    }

    //开启事务
    @Transactional
    @Override
    public int createLessonPlan(LessonPlan lessonPlan,String uid) {

        String ask = lessonPlanUtil.buildChat(lessonPlan);
        System.out.println(ask);
        //构建客户端
        OpenAiStreamClient openAiStreamClient = client.openAiStreamClient();
        Message message = Message.builder().role(Message.Role.USER).content(ask).build();
        ChatCompletion chatCompletion = ChatCompletion
                .builder()
                .messages(Collections.singletonList(message))
                .responseFormat(ResponseFormat.builder().type(ResponseFormat.Type.JSON_OBJECT.getName()).build())
                .build();

        //获取输出流客户端
        LessonSseStreamFastGptListener lessonSseStreamFastGptListener=new LessonSseStreamFastGptListener();
        SseEmitter sseEmitter = (SseEmitter) LocalCache.CACHE.get(uid);
        lessonSseStreamFastGptListener.setLessonPlanMapper(ywLessonPlanMapper);
        lessonSseStreamFastGptListener.setSseEmitter(sseEmitter);
        lessonSseStreamFastGptListener.setLessonPlan(lessonPlan);
        lessonSseStreamFastGptListener.setLoginUser(SecurityUtils.getLoginUser());
        //创建流式客户端
        openAiStreamClient.streamChatCompletion(chatCompletion, lessonSseStreamFastGptListener);
        return 1;

    }

    /**
     * 查询教案管理
     *
     * @param lplanId 教案管理主键
     * @return 教案管理
     */
    @Override
    public YwLessonPlan selectYwLessonPlanByLplanId(Long lplanId)
    {
        return ywLessonPlanMapper.selectYwLessonPlanByLplanId(lplanId);
    }

    /**
     * 查询教案管理列表
     *
     * @param ywLessonPlan 教案管理
     * @return 教案管理
     */
    @Override
    public List<YwLessonPlan> selectYwLessonPlanList(YwLessonPlan ywLessonPlan)
    {
        return ywLessonPlanMapper.selectYwLessonPlanList(ywLessonPlan);
    }

    /**
     * 新增教案管理
     *
     * @param ywLessonPlan 教案管理
     * @return 结果
     */
    @Override
    public int insertYwLessonPlan(YwLessonPlan ywLessonPlan)
    {
        ywLessonPlan.setCreateTime(DateUtils.getNowDate());
        return ywLessonPlanMapper.insertYwLessonPlan(ywLessonPlan);
    }

    /**
     * 修改教案管理
     *
     * @param ywLessonPlan 教案管理
     * @return 结果
     */
    @Override
    public int updateYwLessonPlan(YwLessonPlan ywLessonPlan)
    {
        ywLessonPlan.setUpdateTime(DateUtils.getNowDate());
        return ywLessonPlanMapper.updateYwLessonPlan(ywLessonPlan);
    }

    /**
     * 批量删除教案管理
     *
     * @param lplanIds 需要删除的教案管理主键
     * @return 结果
     */
    @Override
    public int deleteYwLessonPlanByLplanIds(Long[] lplanIds)
    {
        return ywLessonPlanMapper.deleteYwLessonPlanByLplanIds(lplanIds);
    }

    /**
     * 删除教案管理信息
     *
     * @param lplanId 教案管理主键
     * @return 结果
     */
    @Override
    public int deleteYwLessonPlanByLplanId(Long lplanId)
    {
        return ywLessonPlanMapper.deleteYwLessonPlanByLplanId(lplanId);
    }
}
